package com.njit.WeStudy.control;

import com.njit.WeStudy.dao.UserMapper;
import com.njit.WeStudy.dataobject.User;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.List;

import static com.njit.WeStudy.util.Check.checkEmail;

/**
 * @author yuruiqiao
 * @date 2020/1/23
 * @description 邮箱验证码控制类
 */
@Controller
public class EmailController {

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private DefaultKaptcha kaptcha;
    @Resource
    private UserMapper userMapper;
    /**
     * 2020-01-18
     * 发送邮箱验证码
     * */
    @RequestMapping(path = "/sendEmail")
    @ResponseBody
    public String send(HttpSession session,@RequestParam(value = "email") String toEmail){

        MimeMessage message = mailSender.createMimeMessage();
        if(userMapper.selectBy("email",toEmail).size()!=0){
            return "2";//已经注册过的邮箱
        }
        if(!checkEmail(toEmail)){
            return "0";//邮箱格式不正确
        }
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            String code = kaptcha.createText();
            helper.setFrom("1975116165@qq.com");
            helper.setTo(toEmail);
            helper.setSubject("主题：验证码");
            session.setAttribute("emailCode",code);
            message.setText("<h1>"+code+"</h1>","utf-8","html");
        } catch (Exception e) {
            return "0";
        }
        mailSender.send(message);
        return "1";
    }
    /**
     * 2020-01-18
     * 验证信息是否重复(邮箱、电话)
     * */
    @RequestMapping(path = "/checkInfo")
    @ResponseBody
    public String checkInfo(@RequestParam(value = "info") String info,@RequestParam(value = "str")String str){
        if(str!=null){
            List<User> list =  userMapper.selectBy(info,str);
            if(list.size()!=0){
                return "0";//表示重复
            }
            return "1";//表示并不重复
        }
        return "2";//表示传入空值
    }
}
